import React, { useEffect, useRef } from 'react';
import { useRepoStore } from '@/store/useRepoStore';
import { useEditorStore } from '@/store/useEditorStore';

interface FileExplorerProps {
  owner: string;
  repo: string;
}

const FileExplorer: React.FC<FileExplorerProps> = ({ owner, repo }) => {
  const { 
    currentPath, 
    files, 
    fetchContents, 
    setCurrentPath,
    currentBranch,
    isLoading,
    error 
  } = useRepoStore();
  
  const { startEditing } = useEditorStore();

  // 使用 useRef 来存储上一次请求的参数，避免重复请求
  const lastRequestRef = useRef<{
    owner: string;
    repo: string;
    path: string;
    branch: string;
  } | null>(null);

  useEffect(() => {
    if (!currentBranch) return;
    
    // 检查是否与上一次请求参数相同
    const currentRequest = {
      owner,
      repo,
      path: currentPath,
      branch: currentBranch
    };
    
    // 如果参数相同且已有上一次请求记录，则不重复请求
    if (lastRequestRef.current && 
        lastRequestRef.current.owner === currentRequest.owner &&
        lastRequestRef.current.repo === currentRequest.repo &&
        lastRequestRef.current.path === currentRequest.path &&
        lastRequestRef.current.branch === currentRequest.branch) {
      return;
    }
    
    // 更新上一次请求记录并发起请求
    lastRequestRef.current = currentRequest;
    fetchContents(owner, repo, currentPath, currentBranch);
  }, [owner, repo, currentPath, currentBranch, fetchContents]);
  
  // 组件卸载时清除请求记录
  useEffect(() => {
    return () => {
      lastRequestRef.current = null;
    };
  }, []);

  const handleFileClick = async (path: string, isDir: boolean) => {
    if (isDir) {
      // 如果是目录，更新当前路径并获取内容
      setCurrentPath(path);
    } else {
      // 如果是文件，获取文件内容并打开编辑器
      try {
        const response = await useRepoStore.getState().fetchFile(owner, repo, path, currentBranch);
        if (response) {
          // 根据文件扩展名确定语言
          const extension = path.split('.').pop() || '';
          let language = 'plaintext';
          
          // 简单的扩展名到语言映射
          const languageMap: Record<string, string> = {
            'js': 'javascript',
            'jsx': 'javascript',
            'ts': 'typescript',
            'tsx': 'typescript',
            'html': 'html',
            'css': 'css',
            'json': 'json',
            'md': 'markdown',
            'py': 'python',
            'java': 'java',
            'c': 'c',
            'cpp': 'cpp',
            'cs': 'csharp',
            'go': 'go',
            'rb': 'ruby',
            'php': 'php',
            'sh': 'shell',
            'yml': 'yaml',
            'yaml': 'yaml',
            'xml': 'xml',
            'sql': 'sql',
            'kt': 'kotlin',
            'swift': 'swift',
            'rs': 'rust',
          };
          
          if (extension in languageMap) {
            language = languageMap[extension];
          }
          
          startEditing(response.content, language);
        }
      } catch (err) {
        console.error('获取文件内容失败', err);
      }
    }
  };

  const navigateUp = () => {
    // 导航到上一级目录
    if (currentPath === '') return;
    
    const pathParts = currentPath.split('/');
    pathParts.pop(); // 移除最后一个部分
    const newPath = pathParts.join('/');
    setCurrentPath(newPath);
  };

  if (isLoading) {
    return (
      <div className="flex justify-center items-center h-32">
        <div className="animate-spin rounded-full h-6 w-6 border-t-2 border-b-2 border-green-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-sm text-red-600 dark:text-red-400">
        加载文件列表失败: {error}
      </div>
    );
  }

  return (
    <div className="h-full">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-sm font-medium text-gray-900 dark:text-white">文件浏览器</h3>
        {currentPath && (
          <button 
            onClick={navigateUp}
            className="text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
          >
            返回上级
          </button>
        )}
      </div>
      
      <div className="text-xs text-gray-500 dark:text-gray-400 mb-2 truncate">
        当前路径: {currentPath || '/'}
      </div>
      
      <ul className="space-y-1 max-h-[60vh] overflow-y-auto custom-scrollbar">
        {files.length === 0 ? (
          <li className="text-sm text-gray-500 dark:text-gray-400 py-2">此目录为空</li>
        ) : (
          files.map((file) => (
            <li key={file.path} className="group">
              <button
                onClick={() => handleFileClick(file.path, file.type === 'dir')}
                className="w-full text-left px-2 py-1.5 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center text-sm"
              >
                {file.type === 'dir' ? (
                  <svg className="h-4 w-4 text-yellow-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M2 6a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1H8a3 3 0 00-3 3v1.5a1.5 1.5 0 01-3 0V6z" clipRule="evenodd" />
                    <path d="M6 12a2 2 0 012-2h8a2 2 0 012 2v2a2 2 0 01-2 2H2h2a2 2 0 002-2v-2z" />
                  </svg>
                ) : (
                  <svg className="h-4 w-4 text-gray-400 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clipRule="evenodd" />
                  </svg>
                )}
                <span className="truncate text-gray-700 dark:text-gray-300">
                  {file.name}
                </span>
              </button>
            </li>
          ))
        )}
      </ul>
    </div>
  );
};

export default FileExplorer;